<template>
  <section class="tableList">
    <section class="table-list">
        <el-table  :data='data' :size='size'
          :border  ='isBorder'
          @select='select'
          @select-all='selectAll'
          @row-click="clickRow"
          @current-change="handleCurrentChange"
          v-loading='loading'
          :show-header='showHeader'
          :highlight-current-row='!multiple'
          :defaultSelections='defaultSelections'
          style="width: 100%"
          :row-Key="'id'"
          :tree-props="{children: 'children',hasChildren: 'isLeaf'}"
          ref="tableList">
            <el-table-column v-if="isExtend" type="expand">
              <template slot-scope="props">
                <component :is="expandComponent.name" :rowData="props.row" v-on:refresh="refresh" :ref="props.ref"></component>
              </template>
            </el-table-column>
            <el-table-column v-if="isSelection" type="selection" align="center" :reserve-selection="reserveSelection" ></el-table-column>
            <el-table-column v-if="isIndex" type="index" :index="autoindex" :label="indexLabel" align="center" width="50">
						</el-table-column>
            <!-- 数据栏 -->
            <el-table-column v-for="(column, index) in columns" :sortable="column.sortable"
              :key="index" :prop="column.prop" :label="column.label" :min-width="column.minWidth" :width="column.width" :align="column.align" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <template v-if="!column.render">
                  <template v-if="column.formatter">
                    <span v-html="column.formatter(scope.row, column)"></span>
                  </template>
                  <template v-else>
                    <el-input type="text" size="mini" v-model="scope.row[column.prop]" v-if="scope.row.edit && (!column.type || column.type == 'input') && column.edit"></el-input>
                    <el-input type="number" size="mini" :minlength="column.minlength" v-model="scope.row[column.prop]" v-if="scope.row.edit && column.type == 'number'" style="width:80%" @input="column.method(scope.row,$event)"></el-input>
                    <span v-if="!scope.row.edit">{{scope.row[column.prop]}}</span>
                    <template v-else>
                      <span v-if="!column.edit">
                        {{scope.row[column.prop]}}
                      </span>
                    </template>
                  </template>
                </template>
                <template v-else>
                  <expand-dom :column="column" :row="scope.row" :render="column.render" :index="index" :rowIndex="scope.$index" :ref="column.ref"></expand-dom>
                </template>
              </template>
            </el-table-column>
            <template v-if="isOperates">
              <el-table-column ref="fixedColumn" label="操作" align="center" :min-width="operates.minWidth" :width="operates.width" :fixed="operates.fixed"
                    v-if="operates && (!operates.type || operates.type == 'button') && operates.list.filter(_x=>_x.show === true).length > 0">
                <template slot-scope="scope">
                  <!-- 需结合operates.list使用 可参考 jurisdictionManageOpen页面 -->
                  <template v-if="operates.tipType == 'popconfirm'">
                      <el-popconfirm :title="operates.config.tipTitle" :confirm-button-text="operates.config.trueBtn"
                        :cancel-button-text="operates.config.falseBtn" @confirm="operates.config.method(scope.row)">
                        <div class="tablePopconfirm" slot="reference"><span>{{operates.config.text}}</span></div>
                      </el-popconfirm>
                  </template>
                  <template v-else>
                    <template v-for="(btn, key) in operates.list">
                      <el-button :type="btn.type" :size="size" :icon="btn.icon" :disabled="btn.disabled" v-if="btn.show && (!scope.row.hiddeMenus || scope.row.hiddeMenus && scope.row.hiddeMenus.filter(item=>item.id == btn.id).length == 0)" :key='btn.id'
                        :plain="btn.plain" @click.native.stop.prevent="btn.method(key,scope.row, scope.$index)">{{ btn.label }}
                      </el-button>
                      <el-divider direction="vertical" v-if="key < operates.list.length - 1 && (!scope.row.hiddeMenus || scope.row.hiddeMenus && scope.row.hiddeMenus.filter(item=>item.id == btn.id).length == 0)" :key="key"></el-divider>
                    </template>
                  </template>
                </template>
              </el-table-column>
              <el-table-column ref="fixedColumn" label="操作" align="center" :min-width="operates.minWidth" :width="operates.width" :fixed="operates.fixed"
                    v-if="operates && operates.type == 'dropdown' && operates.list.filter(_x=>_x.show === true).length > 0">
                <template slot-scope="scope">
                    <el-dropdown v-if="!scope.row.hiddeMenus || (!!scope.row.hiddeMenus && scope.row.hiddeMenus.length < operates.list.length)">
                      <span class="el-dropdown-link">
                        操作<i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <template v-for="(btn, key) in operates.list">
                          <el-dropdown-item class="mini-dropdown-item" @click.native.stop.prevent="btn.method(key,scope.row)" v-if="btn.show && (!scope.row.hiddeMenus || scope.row.hiddeMenus && scope.row.hiddeMenus.filter(item=>item.id == btn.id).length == 0)" :key="key">{{ btn.label }}</el-dropdown-item>
                        </template>
                      </el-dropdown-menu>
                    </el-dropdown>
                </template>
              </el-table-column>
            </template>
        </el-table>
    </section>
  </section>
</template>

<script>
import Vue from 'vue'
export default {
  name: 'list',
  props: {
    url: String,
    // 表格型号：mini,medium,small
    size:{type:String, default:'medium'},
    isBorder:{type:Boolean, default:false},
    loading:{type:Boolean, default:false},
    isOperates: {type:Boolean, default:true}, // 是否需要操作栏
    showHeader:{type:Boolean, default:true},
    tableHandles:{type:Array, default:()=>[]},
    // 表格列配置
    columns:{ type:Array, default:()=>[]},
    // 表格数据
    data:{ type:Array, default:()=>[]},
    // 操作按钮组 label: 文本，type :类型（primary / success / warning / danger / info)
    operates: {},
    // 是否显示表格复选框
    isSelection:{type:Boolean, default:false},
    reserveSelection:{type:Boolean, default:false},//是否记录分页选中
    // 是否展开行
    isExtend:{type:Boolean, default:false},
    // 展开行内容
    expandColumn: {type:Object, default:()=>{}},
    defaultSelections:{ type:[Array,Object], default:()=>null},
    // 是否显示表格索引
    isIndex:{type:Boolean, default:false},
		indexLabel: {type:String, default:'序号'},
		autoindex:{type:Function},
    expandComponent: {type: Object, default:()=>{}},
    rowKey:{type:String, default:()=>'id'},
    enableEdit:{type:Boolean, default:false}, //是否可编辑
    multiple:{type:Boolean, default:true}, //是否可多选
    showSummary:{type:Boolean, default:false},//是否显示合计
    sumText:{type:String, default:'合计'},//合计字段名称
  },
  components: {
    expandDom: {
      functional: true,
      props: {
        row: Object,
        render: Function,
        rowIndex: Number,
				index: Number,
        column: {
          type: Object,
          default: null
        }
      },
      render: (h, ctx) => {
        const params = {
          row: ctx.props.row,
          index: ctx.props.index,
					rowIndex: ctx.props.rowIndex,
					ref:ctx.props.column.ref
        }
        if (ctx.props.column) {
          params.column = ctx.props.column
        }
        return ctx.props.render(h, params)
      }
    }
  },
  data(){
    return {
    }
  },
  created: function(){
    this.$on('update', function(){
      this.$refs.tableList.bodyWrapper.scrollTop = 0;
    });
    if(this.expandComponent){
      this.registerComponent(this.expandComponent);
		}
  },
  mounted() {
    //TODO 计算高度
  },
  methods: {
    //单选
    handleCurrentChange(row){
      if(!this.isSelection){
        this.$emit('handleSelect', row)
      }
    },
    // 表格勾选
    select(rows,row){
      this.$emit('handleSelect', rows,row)
    },
    // 全选
    selectAll(rows){
      this.$emit('handleSelect',rows)
    },
    //单击行
    clickRow(row, column, event){
      if(this.enableEdit){
        this.data.forEach(element => {
          element.edit = false;
        });
        row.edit = true;
        this.$set(this.data, event.currentTarget.rowIndex, row)
      }
    },
    //保存行
    getEditData(){
      return this.data
    },
    //刷新
    refresh(data){
			if(data){
        this.$emit('refresh',data)
			}else{
        this.$emit('refresh')
			}
    },
    getRowKey(row){
      if(Array.isArray(this.rowKey)){
        var keys = []
        this.rowKey.forEach(element => {
          keys.push(row[element])
				})
        return keys.join('_')
      }else{
        return row[this.rowKey]
      }
    },
    registerComponent(expand){
			var url = expand.moduleType + '/' + expand.name;
      return import('@/views/' + url + '.vue').then((component) => {
        return Vue.component(expand.name, component.default)
      })
    },
    // 带建议输入框
    querySearchAsync(queryString, cb,key) {
      for(let i of this.columns){
        if(i.type == "autocomplete"){
          if(i.method){
            let lists = i.method(i.url,i.remote)
            lists.then((e)=>{
              if(e.key == key){
                let data = e.list
                var results = queryString ? data.filter(this.createStateFilter(queryString,e.checkKey)) : data;
                cb(results);
              }
            })
          }
        }
      }

    },
    // 规则
    createStateFilter(queryString,checkKey) {
      return (state) => {
        if(checkKey){
          return (state.label.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        }
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    // 建议输入框
    handleAutoComplete(val,state){
      let data = {
        value: val.value ? val.value : val,
        state:state
      }
      this.$emit('handleAutoComplete', data)
    },
    // 清空选择
    clearSelect(){
      this.$refs.tableList.clearSelection()
    },
  },
  watch:{
    'data'(value){
      value.forEach(element => {
        if(typeof element.edit == 'undefined'){
          element.edit = false
        }
      });
    },
    'defaultSelections'(val) {
        this.$nextTick(function(){
          if(Array.isArray(val)){
            val.forEach(row=>{
              this.$refs.tableList.toggleRowSelection(row)
            })
          }else{
            this.$refs.tableList.toggleRowSelection(val)
          }
        })
    },
  }
}
</script>
<style lang="less">
  .table-list .cell {
    .el-dropdown{
      font-size: 12px;
      color: #068bff;
      cursor: pointer;
    }
    .el-button--text {
      font-weight: normal;
      font-size: 12px;
    }
  }
  .mini-dropdown-item.el-dropdown-menu__item{
    font-size: 12px;
  }
  .gray-bg td.el-table__expanded-cell {
    background: #f8f8f8;
  }
  .gray-bg .el-table__expanded-cell:hover {
    background-color: #f8f8f8 !important;
  }
  .el-table--enable-row-transition .el-table__body td.el-table__expanded-cell {
    -webkit-transition: none;
    transition: none;
  }
  .el-table td div.el-tabs {
    background: #fff;
    padding: 15px;
    border: 1px solid rgb(244, 244, 244);
  }
  .tableList > .table-list > .el-table > div > table > tbody > tr > td.el-table__expanded-cell,
  .tableList > .table-list > .el-table > div > table > tbody > tr > td.el-table__expanded-cell:hover {
    background: #fbfbfb !important;
    padding: 20px 30px;
  }

  .tablePopconfirm{
    min-height: 30px;
    color: #409EFF;
    line-height: 30px;
    cursor: pointer;
  }

  .el-autocomplete-suggestion .el-scrollbar{
    .el-autocomplete-suggestion__wrap li{
      width: 100%;
      padding:0 10px;
    }
  }

</style>
